﻿#include <iostream>
#include <fstream>
#include <string> 
#include <vector>
#include <stdio.h>
#include"MessagePro.h"
#include"tools.h"
using namespace std;

void printInfo() {
	cout << "List of all DBMS commands:" << endl;
	cout << "help (\\h):Display this help." << endl;
	cout << "quit (\\q):Quit DBMS." << endl;
	cout << "use :Use another database.Takes database name as argument." << endl;
}
//去掉字符串中某个特殊子字符串

int main(int argc, char *argv[])
{
	string userName = "", pwd = "";
	string ip = "127.0.0.1";
	int port = 8080;
	string info = "";
	string str = "";
	for (int i = 0; i < argc; i++)
	{
		if (strcmp(argv[i], "-u") == 0)
			userName = argv[i + 1];
		else if (strcmp(argv[i], "-p") == 0)
			pwd = argv[i + 1];
		else if (strcmp(argv[i], "-h") == 0)
			ip = argv[i + 1];
		else if (strcmp(argv[i], "-P") == 0)
			port = atoi(argv[i + 1]);
	}

	CString cip;
	cip = ip.c_str();
	MessagePro pro(cip, port);
	if (!pro.Init()) {
		getchar();
		return 0;
	}
	//pro.SendMsg(  "root|123" );
	pro.SendMsg(userName + "|" + pwd);
	if (!pro.ReceiveLoginInfo(info)) {
		exit(0);
	}
	do {
		printf("sql->");
		getline(cin, str);
		if (str == "")
			continue;
		if (str == "\\q") {
			cout << "Bye !" << endl;
			exit(0);
		}
		if (str == "\\h" || str == "help") {
			printInfo();
			continue;
		}
		if (str.at(str.length() - 1) == ';') {
			str = str.substr(0, str.length() - 1);
		}
		if (str.substr(0, 6) == "source") {
			if (!ReadSqlFile(str.substr(6, str.length() - 6), pro)) {
				getchar();
				exit(0);
			}
			continue;
		}
		pro.SendMsg(str.c_str());
		if (!pro.ReceiveMsg()) {
			cout << "服务器连接断开！" << endl;
			getchar();
			break;
		}
	} while (str != "#");
	return 0;
}
